import { BellOutlined, CloseOutlined, DownOutlined, LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import { message, UploadProps } from "antd";
import Upload, { RcFile, UploadChangeParam, UploadFile } from "antd/lib/upload";
import axios from "axios";
import { useEffect, useRef, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import Main from "../view/login/Main";

// import UpdateContent from "./UpdateContent";
interface Iidea {
    tags: string,
    flag: boolean,
    info: string
}
function NavTop() {
    let [className, setclassName] = useState('nav');
    let [visiable1, setvisiable1] = useState("")
    let [visiable2, setvisiable2] = useState("none")
    let [tan, settan] = useState("none")

    const navigate = useNavigate();
    let avatar=sessionStorage.getItem("avatar") as string
    function Tologin() {
        navigate({ pathname: '/login' });
    }

   function UpData(){
    settan("block")
   }
    function Toregister() {
        navigate({ pathname: '/register' });
    }
    
    function ToSearch() {
        navigate({ pathname: '/search' });
    }
    function ToDynamic() {
        navigate({ pathname: '/Dynamic' });
    }
    
    function ToHomePage() {
        navigate({ pathname: '/' });
    }
    useEffect(() => {
        if(sessionStorage.getItem("uid")){
            setvisiable1("none")
            setvisiable2("")
        }
        window.onscroll = () => {
            let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
            // console.log(scrollTop);
            if (scrollTop > 60) {
                setclassName('newnav')
            } else {
                setclassName('nav')
            }

        }

    }, [])



    const fileRef = useRef<any>();
    const workName = useRef<any>();
    const inputinner = useRef<any>();
    const description = useRef<any>();
    const divref = useRef<any>();

    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();
    const getBase64 = (img: RcFile, callback: (url: string) => void) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result as string));
        reader.readAsDataURL(img);

    };

    const beforeUpload = (file: RcFile) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    };

    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj as RcFile, url => {

                setLoading(false);
                setImageUrl(url);
                let cover = info.file.response.data.url
                localStorage.setItem("cover", cover)
            });
        }
    };


    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );


    const arr = [
        { tags: '分类', info: '分类', flag: true },
        { tags: '人像', info: '人像', flag: false },
        { tags: '黑白', info: '黑白', flag: false },
        { tags: '风光', info: '风光', flag: false },
        { tags: '纪实', info: '纪实', flag: false },
        { tags: '街头', info: '街头', flag: false },
        { tags: '建筑', info: '建筑', flag: false },
        { tags: '观念', info: '观念', flag: false },
        { tags: '静物', info: '静物', flag: false },
        { tags: '体育', info: '体育', flag: false },
        { tags: '动物', info: '动物', flag: false },
        { tags: '植物', info: '植物', flag: false },
        { tags: '食品', info: '食品', flag: false },
        { tags: '插画', info: '插画', flag: false },
        { tags: '时尚', info: '时尚', flag: false },
        { tags: '其他', info: '其他', flag: false },
    ]
    const [list, setlist] = useState<Iidea[]>(arr)
    function getValue() {
        for (let i = 0; i < list.length; i++) {
            let obj = list[i];
            if (obj.flag == true) {
                return obj.info;
            }

        }
    }

    function changeE(e: any) {
        let v = e.target.value;
        let newList = [...list];
        for (let i = 0; i < newList.length; i++) {
            let obj = newList[i];
            if (obj.info == v) {
                obj.flag = true;
            } else {
                // console.log(obj.tags);
                obj.flag = false;
            }
        }
        setlist(newList);
    }
    const [display, setDisplay] = useState('none')
    function updataBtn() {
        setDisplay('flex')
    }
    function submitBtn() {
        let cover = localStorage.getItem('cover')
        let title = workName.current.value
        let abstrucont = inputinner.current.value;
        let descc = description.current.value
        let tags = '';
        for (let i = 0; i < list.length; i++) {
            let obj = list[i];
            if (obj.flag == true) {
                tags = obj.tags
            }
        }
        console.log(tags);
        
        axios.post('http://127.0.0.1:81/setdynamics', {
            cover, tags, title, abstrucont, descc
        }).then(function (res) {
            console.log(res);
        })
            .catch(function (error) {
                console.log(error);
            });



    }
    return (
        <div className={className}>
            <div className="nav-left">
                <span >
                    <img src="https://7mx.com/static/img/m.8f17855.svg" alt="" />
                    <img src="https://7mx.com/static/img/7MX.350f9fc.svg" alt="" />
                </span>
                <div className="search">
                    <span >图片</span>
                    <span><DownOutlined style={{ fontWeight: 'bolder' }} /></span><span style={{ marginLeft: '5px' }} >|</span>
                    <input type="text" placeholder="搜索" />
                    <span className="searchImg"><img src={require('../image/search.png')} alt="" /></span>
                </div>
            </div>
            <div className="nav-middle">
                <div onClick={ToHomePage}>首页</div>
                {/* <div>首页</div> */}
                <div onClick={ToDynamic}>动态</div>
                <div onClick={ToSearch}>探索</div>
                <div>活动</div>
                <div>榜单</div>
                <div>商店</div>
                <div>关于</div>
            </div>
            <div className="nav-right" style={{ display: visiable1 }} >
                <div>签约</div>
                <div onClick={updataBtn}>上传</div>
                <div onClick={Toregister}>注册</div>
                <div onClick={Tologin}>登录</div>
            </div>
            <div className="nav-right" style={{ display: visiable2 }}>
                <div onClick={UpData}>设置</div>
                <div onClick={updataBtn}>上传</div>
                <div><BellOutlined style={{ fontSize: "24px" }} /></div>
                <div><img src={avatar} alt="" style={{ height: "40px", width: "40px", borderRadius: "50%" }} /></div>
            </div>
            {/* 上传 */}
            <div >
                <div className="updataBox" style={{ display }}>
                    <div className="upbox">
                        <div onClick={() => setDisplay('none')}>
                            <CloseOutlined style={{ fontSize: '28px', marginLeft: '970px', color: '#ccc' }} />
                        </div>
                        <div className="inputbox">

                            <Upload
                                name="avatar"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action="http://127.0.0.1:81/upload"
                                beforeUpload={beforeUpload}
                                onChange={handleChange}
                                style={{ height: "200px", width: "200px" }}
                            >
                                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%', height: '100%' }} /> : uploadButton}
                            </Upload>
                            <div>
                                <input type="text" className="workName" placeholder="作品名称" ref={workName} />
                            </div>
                            <div>
                                <textarea className="description" id="" cols={30} rows={10} placeholder="描述性图片的故事，有利于推荐！" ref={description}></textarea>
                            </div>
                            <select value={getValue()} onChange={changeE} style={{ width: '500px', height: "40px", borderColor: 'rgb(227, 227, 227)' }}>
                                {
                                    list.map((obj, index) => {
                                        return (
                                            <option key={obj.tags} value={obj.info}>{obj.info}</option>
                                        );
                                    })
                                }
                            </select>
                            <div>
                                <input type="text" className="workName" placeholder="添加关键词描述" ref={inputinner} />
                            </div>
                        </div>
                        <div className="activBtn" onClick={submitBtn}>发布</div>
                    </div>
                </div>
            </div>
        </div>
    );
}
export default NavTop;